/*
 * @File name:
 * @Author: 1079161148@qq.com
 * @Version: V1.0
 * @Date: 2025-02-28 13:14:01
 * @Description:
 * Copyright (C) 2024-{year} Tsing Micro Technology Inc All rights reserved.
 */
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'
import { visualizer } from 'rollup-plugin-visualizer'
import viteCompression from 'vite-plugin-compression'
import { createHtmlPlugin } from 'vite-plugin-html'

// 环境变量配置
const envConfig = {
  development: {
    VITE_API_BASE_URL: '/api',
  },
  production: {
    VITE_API_BASE_URL: 'https://api.example.com',
  },
} as const

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd())
  const isBuild = command === 'build'

  return {
    plugins: [
      vue(),
      // 自动导入组件
      Components({
        resolvers: [VantResolver()],
        dts: 'src/types/components.d.ts',
      }),
      // 自动导入 API
      AutoImport({
        imports: [
          'vue',
          'vue-router',
          'pinia',
          {
            vant: ['showToast', 'showDialog', 'showNotify', 'showLoading'],
          },
        ],
        dts: 'src/types/auto-imports.d.ts',
      }),
      // HTML 压缩和环境变量注入
      createHtmlPlugin({
        minify: isBuild,
        inject: {
          data: {
            title: env.VITE_APP_TITLE,
          },
        },
      }),
      // Gzip 压缩
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: 'gzip',
        ext: '.gz',
      }),
      // 打包分析
      visualizer({
        open: true,
        gzipSize: true,
        brotliSize: true,
        filename: 'dist/stats.html',
      }),
    ],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
        '@components': resolve(__dirname, 'src/components'),
        '@views': resolve(__dirname, 'src/views'),
        '@stores': resolve(__dirname, 'src/stores'),
        '@utils': resolve(__dirname, 'src/utils'),
        '@assets': resolve(__dirname, 'src/assets'),
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          additionalData: `@import "@/styles/variables.less";`,
        },
      },
      // CSS 代码分割
      modules: {
        scopeBehaviour: 'local',
        generateScopedName: '[name]__[local]___[hash:base64:5]',
      },
    },
    server: {
      host: true,
      port: 3000,
      proxy: {
        '/api': {
          target: env.VITE_APP_BASE_API,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
    build: {
      target: 'es2015',
      outDir: 'dist',
      assetsDir: 'assets',
      assetsInlineLimit: 4096, // 4kb
      cssCodeSplit: true,
      sourcemap: mode !== 'production',
      // 生产环境移除 console
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: mode === 'production',
          drop_debugger: mode === 'production',
        },
      },
      // 分块策略
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks: {
            'vue-vendor': ['vue', 'vue-router', 'pinia'],
            vant: ['vant'],
            utils: ['marked', 'dompurify'],
          },
        },
      },
      // 启用 brotli 压缩
      brotliSize: true,
      // chunk 大小警告的限制
      chunkSizeWarningLimit: 2000,
    },
    // 预构建配置
    optimizeDeps: {
      include: ['vue', 'vue-router', 'pinia', 'vant', 'marked', 'dompurify'],
    },
    define: {
      'process.env': envConfig[mode as keyof typeof envConfig],
    },
  }
})
